package com.appheader.webfragmentviewpagertest;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.appheader.webfragmentviewpagertest.adapter.HorizontalRecyclerAdapter;
import com.appheader.webfragmentviewpagertest.utils.UITools;
import com.appheader.webfragmentviewpagertest.views.HorizontalRecyclerview;
import com.appheader.webfragmentviewpagertest.views.MyHorizontalScroll;
import com.appheader.webfragmentviewpagertest.views.MyHorizontalViewPager;
import com.appheader.webfragmentviewpagertest.views.MyWebView;
import com.appheader.webfragmentviewpagertest.views.PagerAdapter;
import com.appheader.webfragmentviewpagertest.views.VerticalViewPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private MyHorizontalViewPager viewPager;
    private PopupWindow mPopupWindow;
    private HorizontalRecyclerview recyclerView1, recyclerView2;
    private RecyclerView.LayoutManager manager1, manager2;
    private HorizontalRecyclerAdapter horizontalRecyclerAdapter;
    private LayoutInflater layoutInflater;
    private LinkedList<View> mViewCache = new LinkedList<>();//用于存储垂直的viewpager
    private List<View> verticalList;
    private List<MyWebView> fragmentList = new ArrayList<>();//用于存储webview
    private FloatingActionButton fab;//悬浮按钮，控制弹出popupwindow

    private Map<Integer, List<String>> listMap = new HashMap<>();//webview假数据
    private Map<Integer, List<Integer>> imgListMap = new HashMap<>();//底部popupwindow菜单小图片的假数据
    private MyHorizontalPagerAdapter myPagerAdapter;
    private List<String> list;
    private WindowManager wm;
    ;private int width;
    private int height;
    private View popupWindow_view;
    private CheckBox switchOffOn;
    private LinearLayout switchLayout;
    //    private HorizontalScrollView horizontalScrollView1;
    private MyHorizontalScroll horizontalScrollView1;
    private HorizontalScrollView horizontalScrollView2;
    //    private  verticalViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setData();
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopupWindow != null) {
//                    mPopupWindow.showAsDropDown(findViewById(R.id.show_hide_fab));
                    mPopupWindow.dismiss();
                } else {
                    initPop();

//                    mPopupWindow.showAsDropDown(findViewById(R.id.show_hide_fab));
                }
            }
        });
//        getParent().requestDisallowInterceptTouchEvent(true);
//        viewPager.requestDisallowInterceptTouchEvent(false);
    }



    //构建数据源
    private void setData() {
        List<Integer> list1 = new ArrayList<>();
        list1.add(R.mipmap.ic_launcher);
        list1.add(R.mipmap.banner2);
        list1.add(R.mipmap.banner3);
        list1.add(R.mipmap.banner4);
        List<Integer> list2 = new ArrayList<>();
//        list2.add(R.mipmap.im01);
        list2.add(R.mipmap.sea);
        list2.add(R.mipmap.welcom);
//        list2.add(R.mipmap.im3);
        list2.add(R.mipmap.ic_launcher);
        imgListMap.put(0, list1);
        imgListMap.put(1, list2);
    }

    //初始化popupwindow
    private void initPop() {
        wm = this.getWindowManager();
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();
        popupWindow_view = LayoutInflater.from(this).inflate(R.layout.pop_test, null, false);

        popupWindow_view.setFocusable(true);
        popupWindow_view.setFocusableInTouchMode(true);
        mPopupWindow = new PopupWindow(popupWindow_view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        //初始设置高度为屏幕的1/4，宽度为填充父窗口
//        mPopupWindow.setWidth(width);
//        mPopupWindow.setHeight(height / 2);
        // 设置点击其他地方消失
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (mPopupWindow != null && mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                    mPopupWindow = null;
                }
                return false;
            }
        });
        //设置点击返回键时popupwindow消失
        popupWindow_view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    mPopupWindow.dismiss();
                    mPopupWindow = null;
                    return true;
                }
                return false;
            }
        });

        mPopupWindow.setFocusable(true);//可点击
        mPopupWindow.setOutsideTouchable(true);
        //设置位置
        mPopupWindow.showAtLocation(popupWindow_view,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

//        mPopupWindow.update();
        //设置pop显示消失
        mPopupWindow.setAnimationStyle(R.style.BottomMenuAnim);
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        //例化一个ColorDrawable颜色为半透明
//        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        switchOffOn = (CheckBox) popupWindow_view.findViewById(R.id.switch_off_on);//
        switchLayout = (LinearLayout) popupWindow_view.findViewById(R.id.switch_layout);
        recyclerView1 = (HorizontalRecyclerview) popupWindow_view.findViewById(R.id.recycler_first);
        recyclerView2 = (HorizontalRecyclerview) popupWindow_view.findViewById(R.id.recycler_second);

        horizontalScrollView1 = (MyHorizontalScroll) popupWindow_view.findViewById(R.id.scroll_first);
        //设置回弹效果
        UITools.elasticPadding((MyHorizontalScroll) popupWindow_view.findViewById(R.id.scroll_first), 300);

        horizontalScrollView2 = (HorizontalScrollView) popupWindow_view.findViewById(R.id.scroll_second);
        UITools.elasticPadding((HorizontalScrollView) popupWindow_view.findViewById(R.id.scroll_second), 300);
        manager1 = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
        manager2 = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
        recyclerView1.setLayoutManager(manager1);//manager只能给一个recyclerview布局设置
        recyclerView2.setLayoutManager(manager2);

        //设置适配器
        horizontalRecyclerAdapter = new HorizontalRecyclerAdapter(imgListMap, getApplicationContext());

        recyclerView1.setAdapter(horizontalRecyclerAdapter);
        recyclerView2.setAdapter(horizontalRecyclerAdapter);


        horizontalScrollView1.setVisibility(View.VISIBLE);
        horizontalScrollView2.setVisibility(View.GONE);

        switchOffOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (horizontalScrollView1.getVisibility() == View.VISIBLE) {
                    horizontalScrollView1.setVisibility(View.GONE);
                    horizontalScrollView2.setVisibility(View.VISIBLE);


                } else {
                    horizontalScrollView1.setVisibility(View.VISIBLE);
                    horizontalScrollView2.setVisibility(View.GONE);
                }

            }
        });

        switchLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (horizontalScrollView1.getVisibility() == View.VISIBLE) {
                    horizontalScrollView1.setVisibility(View.GONE);
                    horizontalScrollView2.setVisibility(View.VISIBLE);
                    switchOffOn.setChecked(false);


                } else {
                    horizontalScrollView1.setVisibility(View.VISIBLE);
                    horizontalScrollView2.setVisibility(View.GONE);
                    switchOffOn.setChecked(true);
                }
            }
        });

        //在一个布局上动态切换popupwindow高度
//        switchOffOn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (isChecked){
//                    image1.setVisibility(View.GONE);
//                    image2.setVisibility(View.VISIBLE);
//                }else {
//                    image1.setVisibility(View.VISIBLE);
//                    image2.setVisibility(View.GONE);
//                }
//            }
//        });
        //同时请求网络加载图片数据
    }

    private void initView() {
        List<String> list2 = new ArrayList<>();
        list2.add("http://member.jibangong.com/login.html");
        list2.add("http://www.jibangong.com/updates/");
        list2.add("http://www.jibangong.com/help/");
        List<String> list3 = new ArrayList<>();
        list3.add("http://www.jibangong.com/updates/");
        list3.add("http://member.jibangong.com/login.html");
        list3.add("http://www.jibangong.com/updates/");
        list3.add("http://www.jibangong.com/help/");
        layoutInflater = getLayoutInflater();
        listMap.put(0, list2);
        listMap.put(1, list3);

        viewPager = (MyHorizontalViewPager) findViewById(R.id.horizontal_viewpager);
        fab = (FloatingActionButton) findViewById(R.id.show_hide_fab);


        verticalList = new ArrayList<>();
        for (int i = 0; i < listMap.size(); i++) {

            View view = layoutInflater.inflate(R.layout.fragment_web, null);

            VerticalViewPager verticalViewPager = (VerticalViewPager) view.findViewById(R.id.vertical_viewpager);
            verticalViewPager.setAdapter(new MyVerticalPagerAdapter(i, getApplicationContext()));
            verticalList.add(view);//在这里
            for (int j = 0; j < listMap.get(i).size(); j++) {
                fragmentList.add((MyWebView) layoutInflater.inflate(R.layout.webview_layout,null));
            }
        }

        myPagerAdapter = new MyHorizontalPagerAdapter();
        viewPager.setAdapter(myPagerAdapter);
        //可以设置setOffscreenPageLimit(2)，保持当前页的前两页和后两页。
//        viewPager.setOffscreenPageLimit(2);
//        FragmentManager fm =getSupportFragmentManager();
//        myPagerAdapter = new MyPagerAdapter(fm);
//        viewPager.setAdapter(myPagerAdapter);
//        viewPager.addOnPageChangeListener(this);
    }

    //垂直的adapter
    public class MyVerticalPagerAdapter extends PagerAdapter {
        private int mPosition;
        private Context context;

        public MyVerticalPagerAdapter(int position, Context context) {
            mPosition = position;
            this.context = context;
        }
        @Override
        public int getCount() {
            return listMap.get(mPosition).size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            list = listMap.get(mPosition);//通过键position获取到map中的值value

            //简单展示
//            MyWebView webView = new MyWebView(getApplicationContext());
//            webView.loadUrl(list.get(position));
//                    ((VerticalViewPager) container).addView(webView);
////                }
//            }

            //方案一
            ViewHolder viewHolder = null;
            View convertView = null;
            if (mViewCache.size() == 0) {
//            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.webview_layout2, null);
                viewHolder = new ViewHolder();

                viewHolder.myWebView = (MyWebView) convertView.findViewById(R.id.myWebView);
//                viewHolder.myWebView = myWebView;

//                WebView webView;
//                webView = (WebView) convertView.findViewById(R.id.myWebView);
//                viewHolder.webView = (WebView) convertView.findViewById(R.id.myWebView);

//                viewHolder.webView.getSettings().setAppCacheEnabled(true);
//                viewHolder.webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
                convertView.setTag(viewHolder);
                Log.e("TAG", "instantiateItem: 1" );
            } else {

                convertView = mViewCache.removeFirst();
                viewHolder = (ViewHolder) convertView.getTag();
                Log.e("TAG", "instantiateItem: 2" );
        }
            Log.e("TAG", "instantiateItem: "+list.get(position) );
//            viewHolder.webView.loadUrl(list.get(position));
            viewHolder.myWebView.loadUrl(list.get(position));
            container.addView(convertView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            // 这是把webview 中的硬件加速关闭。设置LAYER_TYPE_SOFTWARE后会把当前view转为bitmap保存。这样就不能开多个webview，否则会报out of memory。
//            viewHolder.myWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
//            viewHolder.myWebView.loadUrl(list.get(position));

            //TODO 回调来自HorizontalRecyclerAdapter的位置信息
            /**
             * 应该传递过来两个position，第一个是水平recyclerview的位置hPosition，第二个是垂直recyclerview的位置vPosition
             *
             */
//            if (horizontalRecyclerAdapter!=null){
//
//                horizontalRecyclerAdapter.setOnPositionListener(new OnHorizontalRecyclerViewListener() {
//                    @Override
//                    public void onItemPosition(View v, int hPosition, int vPosition) {
//                        Log.e("ContentActivity", "onItemPosition: "+hPosition+"---------------"+vPosition);
//
//                    }
//                });


//            int hPosition = horizontalRecyclerAdapter.map.get("hPosition");
//            int vPosition = horizontalRecyclerAdapter.map.get("vPosition");
//            Log.e("ContentActivity", "onItemPosition: "+hPosition+"---------------");


//          if (listMap.size() == 0){
//
//          }
            return convertView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            mViewCache.add((View) object);
        }
    }

    public class ViewHolder {
        private MyWebView myWebView;
//        WebView webView;
    }

    //展示水平的数据
    public class MyHorizontalPagerAdapter extends android.support.v4.view.PagerAdapter {

        @Override
        public int getCount() {
            return listMap.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            //方案一
            VerticalViewPager vertical = (VerticalViewPager) verticalList.get(position).findViewById(R.id.vertical_viewpager);
//            webView.loadUrl(webUrl[position]);
            container.addView(vertical);
            //方案二
//            VeritcalViewHolder holder = null;
//            View convertView = null;
//            if (verticalList.size() == 0) {
//                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.fragment_web, null);
////                convertView = fragmentList.get(position).findViewById(R.id.vertical_viewpager);
//                VerticalViewPager viewPager;
//                viewPager = (VerticalViewPager) convertView.findViewById(R.id.vertical_viewpager);
//                holder = new VeritcalViewHolder();
//                holder.verticalView = viewPager;
//                convertView.setTag(holder);
//                Log.e("TAG", "VerticalViewPager1 ");
//            } else {
//                convertView = verticalList.removeFirst();
//                holder = (VeritcalViewHolder) convertView.getTag();
//                Log.e("TAG", "VerticalViewPager2 ");
//            }
//            container.addView(convertView);
//            return convertView;
            return vertical;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
// 方案一
            container.removeView(mViewCache.get(position));
            //方案二
//            container.removeView((View) object);
//            verticalList.add((View) object);
        }

        public class VeritcalViewHolder {
            VerticalViewPager verticalView;
        }

    }
}
